import './index.scss';
import InfiniteScroll from 'react-infinite-scroll-component';
import noResults from '../../assets/no-results.png';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import ContentWrapper from '../../components/ContentWrapper';
import { fetchDataFromApi } from '../../utils/api';
import Spinner from '../../components/Spinner';
import MovieCard from '../../components/MovieCard';

const SearchResult: React.FC = () => {
  const [data, setData] = useState<any>(null);
  const [pageNum, setPageNum] = useState(1);
  const [loading, setLoading] = useState(false);
  const { query } = useParams();

  const fetchInitialData = async () => {
    setLoading(true);
    const res = await fetchDataFromApi(`/search/multi?query=${query}&page=${pageNum}`);
    setData(res);
    setPageNum(pre => pre + 1);
    setLoading(false);
  };

  const fetchNextPageData = async () => {
    const res = await fetchDataFromApi(`/search/multi?query=${query}&page=${pageNum}`);
    if (res.results) {
      setData({
        ...data,
        results: [...data?.results, ...res.results],
      });
    } else {
      setData(res);
    }
    setPageNum(pre => pre + 1);
  };

  useEffect(() => {
    fetchInitialData();
  }, [query]);

  return (
    <div className="searchResultsPage">
      {loading && <Spinner initial={true} />}
      {!loading && (
        <ContentWrapper>
          {data?.results?.length > 0 ? (
            <>
              <div className="pageTitle">
                {`Search ${data?.total_results > 1 ? 'results' : 'result'} of ${query}`}
              </div>
              <InfiniteScroll
                className="content"
                dataLength={data?.results?.length || [].length}
                next={fetchNextPageData}
                hasMore={pageNum <= data.total_pages}
                loader={<Spinner />}
              >
                {data.results.map((item: any, index: number) => {
                  if (item?.media_type === 'person') return;
                  return <MovieCard key={index} data={item} formSearch={true}></MovieCard>;
                })}
              </InfiniteScroll>
            </>
          ) : (
            <span className="resultNotFound">抱歉,未查询到相关信息!</span>
          )}
        </ContentWrapper>
      )}
    </div>
  );
};

export default SearchResult;
